/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package tag;

import java.util.Enumeration;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.BodyContent;
import javax.servlet.jsp.tagext.BodyTagSupport;

/**
 *
 * @author Administrator
 */
public class page extends BodyTagSupport {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    private String url;
    private int counts;
    private int pageSize;
    private int pageNum;

    /** 
     * Creates new instance of tag handler 
     */
    public page() {
        super();
    }

    ////////////////////////////////////////////////////////////////
    ///                                                          ///
    ///   User methods.                                          ///
    ///                                                          ///
    ///   Modify these methods to customize your tag handler.    ///
    ///                                                          ///
    ////////////////////////////////////////////////////////////////
    /**
     * Method called from doStartTag().
     * Fill in this method to perform other operations from doStartTag().
     */
    @Override
    public int doStartTag() throws JspException {
        if(pageNum <= 0){
            pageNum = 1;
        }
        if(pageSize <=0){
            pageSize = 1;
        }
        int pageCounts = (counts + pageSize - 1) / pageSize;
        StringBuilder builder = new StringBuilder();
        builder.append("<form name=\"form1\" method=\"post\" action=\"\"\r\n");
        HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();
        Enumeration en = request.getAttributeNames();
        String name, value;
        while (en.hasMoreElements()) {
            name = (String) en.nextElement();
            value = request.getParameter(name);
            if (name.equals("pageNum")) {
                if (value != null && !"".equals(value.trim())) {
                    pageNum = Integer.parseInt(value);
                }
                continue;
            }
            builder.append("<input type=\"hidden\" name=\"");
            builder.append(name).append("\" value=\"");
            builder.append(value).append("\"/>\r\n");
        }
        builder.append("<input type=\"hidden\" name=\"pageNum\" value=\"");
        builder.append(pageNum).append("\"/>\r\n");
        builder.append("&nbsp;共").append(counts).append("项").append(pageCounts).append("页");
        builder.append("<a href=\"javascript:void(null)\"").append("onclick=\"turnOverPage(1)\">&laquo;&nbsp;首页</a>\r\n");
        if(pageNum == 1){
            builder.append("<sapn>&laquo;&nbsp;上一页</span>\r\n");
        }else{
             builder.append("<a href=\"javascript:void(null)\"").append("onclick=\"turnOverPage(").append(pageNum-1).append(")\">&laquo;&nbsp;上一页</a>\r\n");
        }
        
        int num = 3;
        int pagenumber = pageNum -3;
        if(pagenumber <= 0){
            pagenumber = 1;
        }
        while (num > 0 && pagenumber <pageNum) {
                num--;          
                builder.append("<a href=\"javascript:void(null)\"").append("onclick=\"turnOverPage(")
                        .append(pagenumber).append(")\">").append(pagenumber).append("</a>\r\n");
                pagenumber++;
        }
        builder.append("<span>").append(pageNum).append("</span>\r\n");
        num = 3;
        pagenumber = pageNum ;
        while (pagenumber < pageCounts) {
            num--;
            if (num >= 0) {
                pagenumber++;
                builder.append("<a href=\"javascript:void(null)\"").append("onclick=\"turnOverPage(").append(pagenumber).append(")\">").append(pagenumber).append("</a>\r\n");
            }else{
                break;
            }
        }
        
         if(pageNum == pageCounts){
            builder.append("<sapn>&laquo;&nbsp;下一页</span>\r\n");
        }else{
             builder.append("<a href=\"javascript:void(null)\"").append("onclick=\"turnOverPage(").append(pageNum+1).append(")\">&laquo;&nbsp;下一页</a>\r\n");
        }
         builder.append("<a href=\"javascript:void(null)\"").append("onclick=\"turnOverPage(").append(pageCounts).append(")\">&laquo;&nbsp;尾页</a>\r\n");
         builder.append("<input type=\"text\" size=\"1\" name=\"jumpPage\">");   
         builder.append("<a href=\"javascript:void(null)\"").append("onclick=\"turnOverPage(form1.jumpPage.value)\">").append("&laquo;&nbsp;跳转</a>\r\n");
         
         builder.append("</form>");
         builder.append("<script language=\"javascript\">\r\n");
         builder.append("function turnOverPage(num){\r\n");
         builder.append("var formes = document.form1;\r\n");
         builder.append("num = Number(num);\r\n");
         builder.append("if(num >").append(pageCounts).append("){");
         builder.append("num=").append(pageCounts).append(";}\r\n");
         builder.append("if(num <0){num=1;}\r\n");
         builder.append("form1.pageNum.value=num;\r\n");
         builder.append("form1.action=\"").append(url).append("\";\r\n");
         builder.append("form1.submit();\r\n");
         builder.append("}</script>\r\n");
        
         try {
            pageContext.getOut().println(builder.toString());
        } catch (Exception e) {
            throw new JspException(e);
        }
         return SKIP_BODY;
    }

    /**
     * This method is called after the JSP engine finished processing the tag.
     * @return EVAL_PAGE if the JSP engine should continue evaluating the JSP page, otherwise return SKIP_PAGE.
     * This method is automatically generated. Do not modify this method.
     * Instead, modify the methods that this method calls.
     */
    @Override
    public int doEndTag() throws JspException {
            return EVAL_PAGE;
       
    }

    /**
     * This method is called after the JSP engine processes the body content of the tag.
     * @return EVAL_BODY_AGAIN if the JSP engine should evaluate the tag body again, otherwise return SKIP_BODY.
     * This method is automatically generated. Do not modify this method.
     * Instead, modify the methods that this method calls.
     */
    @Override
    public int doAfterBody() throws JspException {
        try {
            // This code is generated for tags whose bodyContent is "JSP"
            BodyContent bodyCont = getBodyContent();
            JspWriter out = bodyCont.getEnclosingWriter();


        } catch (Exception ex) {
            handleBodyContentException(ex);
        }

        if (theBodyShouldBeEvaluatedAgain()) {
            return EVAL_BODY_AGAIN;
        } else {
            return SKIP_BODY;
        }
    }

    /**
     * Handles exception from processing the body content.
     */
    private void handleBodyContentException(Exception ex) throws JspException {
        // Since the doAfterBody method is guarded, place exception handing code here.
        throw new JspException("Error in page tag", ex);
    }

    /**
     * Fill in this method to determine if the rest of the JSP page
     * should be generated after this tag is finished.
     * Called from doEndTag().
     */
    private boolean shouldEvaluateRestOfPageAfterEndTag() {
        // TODO: code that determines whether the rest of the page
        //       should be evaluated after the tag is processed
        //       should be placed here.
        //       Called from the doEndTag() method.
        //
        return true;
    }

    /**
     * Fill in this method to determine if the tag body should be evaluated
     * again after evaluating the body.
     * Use this method to create an iterating tag.
     * Called from doAfterBody().
     */
    private boolean theBodyShouldBeEvaluatedAgain() {
        // TODO: code that determines whether the tag body should be
        //       evaluated again after processing the tag
        //       should be placed here.
        //       You can use this method to create iterating tags.
        //       Called from the doAfterBody() method.
        //
        return false;
    }

    private boolean theBodyShouldBeEvaluated() {
        // TODO: code that determines whether the body should be
        //       evaluated should be placed here.
        //       Called from the doStartTag() method.
        return true;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public void setCounts(int counts) {
        this.counts = counts;
    }

    public void setPageSize(int pageSize) {
        this.pageSize = pageSize;
    }

    public void setPageNum(int pageNum) {
        this.pageNum = pageNum;
    }
}
